<%@ page language="java" import="java.lang.*"  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
	String path = request.getContextPath();
%>
<div class="row-fluid" style="height: inherit;margin:0px;border: 0px">
	<form id="baseInfor" class="form-horizontal" target="_ifr">
	   <input type="hidden" id="transferId" name="id" value="${transfer.id}" />
  	   <input type="hidden" id="state" name="state" value="${transfer.state}" />
	        <%--一行数据 --%>
	        <div class="row" style="margin:0;padding:0;">
	            <%--移库单号--%>
	            <div class="control-group span6" style="display: inline">
	                <label class="control-label" for="receiptNo" >移库单号：</label>
	                <div class="controls">
	                    <div class="input-append span12" >
	                        <input type="text" id="transferNo" class="span10" name="transferNo"   placeholder="后台自动生成" readonly="readonly" value="${transfer.transferNo}"/>
	                    </div>
	                </div>
	            </div>
				<div class="control-group span6" style="display: inline">
					<label class="control-label" for="houseId" >移库人员：</label>
					<div class="controls">
						<div class="span12" style=" float: none !important;">
							<input type="text" id="userId" class="span10" name="userId"   placeholder="移库人员"/>
						</div>
					</div>
				</div>
	        </div> 	        
  	        <div class="row" style="margin:0;padding:0;">
	            <%--库区--%>
	            <div class="control-group span6" style="display: inline">
	                <label class="control-label" for="houseId" >库区：</label>
	                <div class="controls">
	                    <div class="span12 required" style=" float: none !important;">
	                        <input type="text" id="houseId" class="span10" name="houseId"   placeholder="库区"/>
	                    </div>
	                </div>
	            </div>
	            <%--移库时间--%>
	            <div class="control-group span6" style="display: inline">
	                <label class="control-label" for="receiptUser" >移库时间：</label>
	                <div class="controls">
	                    <div class="span12 required" style=" float: none !important;">
	                        <input type="text" class="form-control date-picker" id="transferTime" name="transferTime" value="${transfer.transferTime}" placeholder="移库时间">
	                    </div>
	                </div>
	            </div>
	        </div>
			<div class="row" style="margin:0;padding:0;">
				<%--移库人员--%>
				<div class="control-group span6" style="display: inline">
					<label class="control-label" for="outLocationId" >移出库位：</label>
					<div class="controls">
						<div class="span12" style=" float: none !important;">
							<input type="text" id = "outLocationId" name="outLocationId" class="span10" placeholder="移出库位"/>
						</div>
					</div>
				</div>
				<div class="control-group span6" style="display: inline">
					<label class="control-label" for="houseId" >移入库位：</label>
					<div class="controls">
						<div class="span12" style=" float: none !important;">
							<input type="text" id = "inLocationId" name="inLocationId" class="span10" placeholder="移入库位"/>
						</div>
					</div>
				</div>
			</div>
  	        <div class="row" style="margin:0;padding:0;">
	            <%--移库人员--%>
	            <div class="control-group span6" style="display: inline">
					<label class="control-label" for="remark" >备注：</label>
					<div class="controls">
						<div class="input-append  span12" >
							<input class="span10" type="text" id="remark" name="remark" placeholder="备注" value="${transfer.remark}">
						</div>
					</div>
				</div>
	        </div>	        
	       <div style="margin-left:10px;">
            <span class="btn btn-info" id="formSave">
		       <i class="ace-icon fa fa-check bigger-110"></i>保存
            </span>
            <span class="btn btn-info" id="formSubmit">
		        <i class="ace-icon fa fa-check bigger-110"></i>&nbsp;提交
            </span>
        </div>	
	</form>
	<div id="materialDiv" style="margin:10px;">
		<!-- 下拉框 -->
		<label class="inline" for="inLocationId1">保质单号：</label>
		<input type="text" id = "inLocationId1" name="inLocationId1" style="width:150px;margin-right:10px;" />
		<button id="addMaterialBtn" class="btn btn-xs btn-primary" onclick="addDetail();">
			<i class="icon-plus" style="margin-right:6px;"></i>添加
		</button>
		<button id="addMaterialBtn1" class="btn btn-xs btn-primary" onclick="delDetail();">
			<i class="icon-remove-sign" style="margin-right:6px;"></i>删除
		</button>
	</div>
	<!-- 表格div -->
	<div id="grid-div-c" style="width:100%;margin:10px auto;">
		<!-- 	表格工具栏 -->
        <div id="fixed_tool_div" class="fixed_tool_div detailToolBar">
             <div id="__toolbar__-c" style="float:left;overflow:hidden;"></div>
        </div>
		<!-- 物料详情信息表格 -->
		<table id="grid-table-c" style="width:100%;height:100%;"></table>
		<!-- 表格分页栏 -->
		<div id="grid-pager-c"></div>
	</div>
</div>
<script type="text/javascript">
var context_path = '<%=path%>';
var transferId=$("#transferId").val();
/* var cust=${sale.customer}; */
var oriDataDetail;
var _grid_detail;        //表格对象
var lastsel2;
var outLocationId=0;
$(".date-picker").datetimepicker({format: 'YYYY-MM-DD HH:mm:ss',useMinutes:true,useSeconds:true});
$("#baseInfor").validate({
   ignore: "", 
   rules:{
      "transferTime":{
         required:true,
      },
      "transferName":{
         required:true,
         remote:{
            cache:false,
            async:false,
            url: "<%=path%>/transfer/isHaveName?transferId="+$("#transferId").val()
         }
      },
      "houseId":{
         required:true,
      },
   },
   messages: {
     "transferTime":{
         required:"请选择日期！"
      },
      "transferName":{
         required:"请输入订单名称！",
         remote:"名称重复！"
      },
      "houseId":{
         required:"请选择库区！",
      },
      
   },
   errorPlacement: function (error, element) {
       layer.msg(error.html(),{icon:5});
       }
});

$("#formSubmit").click(function(){
if($("#transferId").val()!=""){
  layer.confirm("提交后的数据将不能修改，确认提交吗？", function() {
   $.ajax({
   url:context_path+"/transfer/submit?transferId="+$("#transferId").val(),
   type:"post",
   dataType:"JSON",
   success:function (data){
       if(data.result){
          gridReload();
          layer.closeAll();
          layer.msg("提交成功",{time:1200,icon:1});
       }else{
          layer.msg(data.msg,{time:1200,icon:2});
       }
    }
   });
  });
}else{
  layer.msg("请先保存表头",{time:1200,icon:2});
}
});

$("#formSave").click(function(){
 var bean = $("#baseInfor").serialize();
if($('#baseInfor').valid()){
   saveOrUpdate(bean);
}
});

/* 保存、修改 */
function saveOrUpdate(bean){
   $.ajax({
   url:context_path+"/transfer/save",
   type:"post",
   data:bean,
   dataType:"JSON",
   success:function (data){
      if(data.result){
      $("#transferId").val(data.transferId);
      $("#baseInfor #transferNo").val(data.transferNo);
      $("#baseInfor #state").val(data.state);
      transferId=data.transferId;
      gridReload();
      layer.msg("操作成功！",{icon:1,time:1200});
      }else{
      layer.msg("操作失败！",{icon:2,time:1200});
      }
   }
   });

}
//单元格编辑成功后，回调的函数
	var editFunction = function eidtSuccess(XHR){
		 var data = eval("("+XHR.responseText+")"); 
		if(data["msg"]!=""){
			layer.alert(data["msg"]);
		}
		jQuery("#grid-table-c").jqGrid('setGridParam', 
				{
					postData: {
						id:$('#id').val(),
						queryJsonString:""
					} 
				}
		  ).trigger("reloadGrid");
	};
	
  
  	_grid_detail=jQuery("#grid-table-c").jqGrid({
         url : context_path + '/transfer/detailList1?transferId='+transferId,
         datatype : "json",
         colNames : [ '详情主键','物料编号','物料名称','箱子条码','标签','数量','移出库位','移入库位','状态'],
         colModel : [ 
  					  {name : 'id',index : 'id',width : 20,hidden:true}, 
  					  {name : 'materialNo',index:'materialNo',width :20}, 
                      {name : 'materialName',index:'materialName',width : 20}, 
                      {name : 'boxCode',index:'boxCode',width : 20}, 
                      {name : 'rfid',index:'rfid',width : 20}, 
                      {name: 'amount', index: 'amount', width: 20,editable : true,editrules: {custom: true, custom_func: numberRegex},
                        editoptions: {
	                          size: 25,
	                          dataEvents: [
	                              {
	                                  type: 'blur',     //blur,focus,change.............
	                                  fn: function (e) {
	                                	  var $element = e.currentTarget;
	                                	  var $elementId = $element.id;
	                                	  var rowid = $elementId.split("_")[0];
	                                	  var id=$element.parentElement.parentElement.children[1].textContent;
	                                	  var indocType = 1;
	                                	 // var rowData = $("#grid-table-c").jqGrid('getRowData',rowid).id;
	                                		  var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
	                                		  if (!reg.test($("#"+$elementId).val())) {
	                                			  layer.alert("非法的数量！(注：可以有两位小数的正实数)");
	                                			  return;
	                                		  }
	                                	  $.ajax({
	                                		  url:context_path + '/transfer/updateAmount',
	                                		  type:"POST",
	                                		  data:{id:id,amount:$("#"+rowid+"_amount").val()},
	                                		  dataType:"json",
	                                		  success:function(data){
	                                		        if(!data.result){
	                                		           layer.alert(data.msg);
	                                		        }
	                                		        $("#grid-table-c").jqGrid('setGridParam', 
                                							{
                                					    		url : context_path + '/transfer/detailList?transferId='+transferId,
                                								postData: {queryJsonString:""} //发送数据  :选中的节点
                                							}
                                					  ).trigger("reloadGrid");
	                                		      
	                                		  }
	                                	  }); 
	                                  }
	                              }
	                          ]
	                      }
                      },
                       {name : 'outLocationName',index:'outLocationName',width : 20}, 
                       {name : 'inLocationName',index:'inLocationName',width : 20}, 
                       {name : 'state',index:'state',width : 20,
                          formatter:function(cellValue,option,rowObject){
	                    		if(typeof cellValue == 'number'){
	                    			if(cellValue==0){
	                    				return "<span style='color:#d15b47;font-weight:bold;'>未处理</span>";
	                    			}else if(cellValue==1){
	                    				return "<span style='color:#76b86b;font-weight:bold;'>正在处理</span>";
	                    			}else if(cellValue==2){
	                    				return "<span style='color:#44BB8C;font-weight:bold;'>处理完成</span>";
	                    			}
	                    		}else{
	                    			return "异常";
	                    		}
	                    	}
                       }, 
                    ],
         rowNum : 20,
         rowList : [ 10, 20, 30 ],
         pager : '#grid-pager-c',
         sortname : 'ID',
         sortorder : "asc",
         altRows: true,
         viewrecords : true,
         autowidth:true,
         multiselect:true,
		 multiboxonly: true,
         loadComplete : function(data) 
         {
             var table = this;
             setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
             oriDataDetail = data;
         },
    //  cellurl : context_path + "/transfer/updateAmount",
	   cellEdit: true,
	   cellsubmit : "clientArray",
  	   emptyrecords: "没有相关记录",
  	   loadtext: "加载中...",
  	   pgtext : "页码 {0} / {1}页",
  	   recordtext: "显示 {0} - {1}共{2}条数据",
    });
    //在分页工具栏中添加按钮
    $("#grid-table-c").navGrid("#grid-pager-c",{edit:false,add:false,del:false,search:false,refresh:false}).navButtonAdd("#grid-pager-c",{  
  	   caption:"",   
  	   buttonicon:"ace-icon fa fa-refresh green",   
  	   onClickButton: function(){   
  	    $("#grid-table-c").jqGrid('setGridParam', 
				{
  	    			url:context_path + '/transfer/detailList?transferId='+transferId,
					postData: {queryJsonString:""} //发送数据  :选中的节点
				}
		  ).trigger("reloadGrid");
  	   }
  	});
  	
  	$(window).on("resize.jqGrid", function () {
  		$("#grid-table-c").jqGrid("setGridWidth", $("#grid-div-c").width() - 3 );
  		var height = $(".layui-layer-title",_grid_detail.parents(".layui-layer")).height()+
                     $("#baseInfor").outerHeight(true)+$("#materialDiv").outerHeight(true)+
                     $("#grid-pager-c").outerHeight(true)+$("#fixed_tool_div.fixed_tool_div.detailToolBar").outerHeight(true)+
                     $("#gview_grid-table-c .ui-jqgrid-hbox").outerHeight(true);
                     $("#grid-table-c").jqGrid("setGridHeight",_grid_detail.parents(".layui-layer").height()-height);
  	});
  	$(window).triggerHandler('resize.jqGrid');
  	if($("#id").val()!=""){
  		//reloadDetailTableList();   //重新加载详情列表
  	}

  
//将数据格式化成两位小数：四舍五入
 function formatterNumToFixed(value,options,rowObj){
	if(value!=null){
		var floatNum = parseFloat(value);
		return floatNum.toFixed(2);
	}else{
		return "0.00";
	}
 } 
 //数量输入验证
function numberRegex(value, colname) {
    var regex = /^\d+\.?\d{0,2}$/;
    reloadDetailTableList();
    if (!regex.test(value)) {
        return [false, ""];
    }
    else  return [true, ""];
}


     $("#inLocationId").select2({
        placeholder: "移入库位",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/transfer/getSelectInLocation",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date(),
                    transferId:$("#transferId").val(),
                    outLocationId:outLocationId
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }

    });
        $("#outLocationId").select2({
        placeholder: "移出库位",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/transfer/getSelectOutLocation",
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date(),
                    transferId:$("#transferId").val()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
               /*  if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                } */
                return {
                        results: res,
                    };
            },
            cache: true
        }

    });
    $("#outLocationId").change(function(){
      outLocationId=$("#outLocationId").val();
    });
		$("#userId").select2({
        placeholder: "选择移库人员",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/ASNmanage/getSelectUser",
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }

    });
    $("#houseId").select2({
        placeholder: "选择库区",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/area/getSelectArea",
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }

    });
if($("#transferId").val()!=""){
        $.ajax({
			  type:"POST",
			  url:context_path + '/transfer/getTransferInfo',
			  data:{transferId:$('#baseInfor #transferId').val()},
			  dataType:"json",
			  success:function(data){
			    $("#houseId").select2("data", {
                     id: data.transfer.houseId,
                     text: data.transfer.houseName
                });
                $("#userId").select2("data", {
                     id: data.transfer.userId,
                     text: data.transfer.userName
                });
			  }
			  });
}else{
  $('#houseId').val("")
}


//添加物料详情
 function addDetail(){
	  if($("#transferId").val()==""){
		  layer.alert("请先保存表单信息！");
		  return;
	  }
	  if($("#outLocationId").val()==""){
	    layer.alert("请先选择移出库位！");
	    return;
	  }
	  if($("#inLocationId").val()==""){
	    layer.alert("请选择移入库位！");
	    return;
	  }
		  //将选中的物料添加到数据库中
		  $.ajax({
			  type:"POST",
			  url:context_path + '/transfer/saveDetail',
			  data:{transferId:$('#baseInfor #transferId').val(),outLocationId:$("#outLocationId").val(),inLocationId:$("#inLocationId").val()},
			  dataType:"json",
			  success:function(data){
				 // removeChoice();   //清空下拉框中的值
				  if(Boolean(data.result)){
					 layer.msg("添加成功",{icon:1,time:1200});
					 //重新加载详情表格
					 reloadDetailTableList();
				  }else{
					  layer.msg(data.msg,{icon:2,time:1200});
				  }
			  }
		  });
  }
  //工具栏
	 /* $("#__toolbar__-c").iToolBar({
	   	 id:"__tb__01",
	   	 items:[
	   	  	{label:"删除", onclick:delDetail},
	    ]
	  });*/
	//删除物料详情
	function delDetail(){
	   var ids = jQuery("#grid-table-c").jqGrid('getGridParam', 'selarrrow');
	   $.ajax({
	      url:context_path + '/transfer/deleteDetail?ids='+ids,
	      type:"POST",
	      dataType:"JSON",
	      success:function(data){
	         if(data.result){
	           layer.msg("操作成功！");
	            //重新加载详情表格
				reloadDetailTableList();
	         }
	      }
	   });
	}
	 function reloadDetailTableList(){
       $("#grid-table-c").jqGrid('setGridParam', 
				{
  	    			url:context_path + '/transfer/detailList?transferId='+transferId,
					postData: {queryJsonString:""} //发送数据  :选中的节点
				}
		  ).trigger("reloadGrid");
     } 
</script>
